/**
 * created by 小卷毛, 2021-06-16
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.rzico.sbl.viewmodel

import android.content.Context
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.RecyclerView
import com.google.android.flexbox.*
import com.lzg.extend.BaseResponse
import com.lzg.extend.JsonConvert
import com.lzg.extend.jackson.JacksonConvert
import com.lzg.okrx.RxSingleHelper
import com.lzg.okrx.adapter.FlowableBody
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.model.*
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.view.DropPopupWindow
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.applyFlowableSchedulers
import com.xinnuo.common_ui.utils.applySchedulers
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject
import kotlin.text.orEmpty

/**
 * 描 述：会员操作相关
 * 作 者：小卷毛  2021-06-16 17:03
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
class MemberViewModel : DialogViewModel() {

    val mTotalNum = MutableLiveData<String>()
    val mTradeNum = MutableLiveData<String>()

    val mTypeList by lazy {
        listOf(
            FilterData("全部", "", "用户类型", true),
            FilterData("企业", "company", "企业"),
            FilterData("个人", "family", "个人")
        )
    }

    val mTicketList by lazy {
        listOf(
            FilterData("全部", "0", "水票", true),
            FilterData("有水票", "1", "有水票"),
            FilterData("无水票", "2", "无水票")
        )
    }

    val mVipList by lazy {
        listOf(
            FilterData("VIP0", "1", "vip0"),
            FilterData("VIP1", "1", "vip1"),
            FilterData("VIP2", "1", "vip2"),
            FilterData("VIP3", "1", "vip3"),
            FilterData("VIP4", "1", "vip4"),
            FilterData("VIP5", "1", "vip5"),
            FilterData("VIP6", "1", "vip6"),
            FilterData("VIP7", "1", "vip7"),
            FilterData("VIP8", "1", "vip8"),
        )
    }

    val mStateList by lazy {
        listOf(
            FilterData("记账会员", "1", "1"),
            FilterData("改价会员", "2", "1"),
            FilterData("自动派单", "3", "1")
        )
    }

    val mBarrelList by lazy {
        listOf(
            FilterData("有押桶", "1", "1"),
            FilterData("无押桶", "1", "2"),
            FilterData("有借桶", "2", "1"),
            FilterData("无借桶", "2", "2")
        )
    }

    val mReferList by lazy {
        listOf(
            FilterData("无推荐人", "1", "1"),
            FilterData("有推荐人", "1", "2")
        )
    }

    val mTradeList by lazy {
        listOf(
            FilterData("已交易", "1", "1"),
            FilterData("未交易", "1", "2")
        )
    }

    val mSourceList by lazy {
        listOf(
            FilterData("后台添加", "1", "pc"),
            FilterData("APP添加", "1", "app"),
            FilterData("小程序", "1", "applet")
        )
    }

    val mOtherList by lazy {
        listOf(
            FilterData("优惠券", "1", "1"),
            FilterData("备注", "2", "1")
        )
    }

    private val mLeadList = ArrayList<FilterData>()

    /**
     * 会员列表筛选条件
     */
    fun memberFilter(
        context: Context,
        bottom: View,
        action: (MemberFilterData) -> Unit
    ) {
        if (mLeadList.isEmpty())
            getLeadList {
                showFilterDialog(context, bottom) { action(it) }
            }
        else showFilterDialog(context, bottom) { action(it) }
    }

    /**
     * 推广员列表
     */
    private fun getLeadList(onFinish: () -> Unit) {
        requestCommon(
            isLoading = true,
            requestUrl = BaseUrl.memberPro,
            requestMethod = HttpMethod.GET,
            onSuccess = { list ->
                mLeadList.clear()
                list.mapTo(mLeadList) {
                    FilterData(
                        name = it.name.orEmpty(),
                        id = "3",
                        hint = it.id
                    )
                }

                onFinish.invoke()
            }
        )
    }

    /**
     * 会员列表筛选框
     */
    private fun showFilterDialog(
        context: Context,
        bottom: View,
        onNext: (MemberFilterData) -> Unit
    ) {
        var item = MemberFilterData()

        dropFilter = object : DropPopupWindow(
            context.inflate(R.layout.pop_member_filter)
        ) {

            override fun afterInitView(view: View) {
                val mReferItems = ArrayList<FilterData>()

                // 会员等级
                val mLevelView = view.find<RecyclerView>(R.id.pop_level).apply {
                    isNestedScrollingEnabled = false

                    /*
                     * 主轴排列的方向：
                     *     FlexDirection.ROW：水平方向。从左到右
                     *     FlexDirection.COLUMN：垂直方向，从上到下
                     *     FlexDirection.ROW_REVERSE：水平方向，从右到左
                     *     FlexDirection.COLUMN_REVERSE：垂直方向，从下到上
                     * 是否支持换行排列：
                     *     FlexWrap.NOWRAP：不换行
                     *     FlexWrap.WRAP：换行
                     *     FlexWrap.WRAP_REVERSE：反方向换行
                     * 主轴上对齐方式：
                     *     JustifyContent.FLEX_START：左对齐
                     *     JustifyContent.FLEX_END：右对齐
                     *     JustifyContent.CENTER：居中
                     *     JustifyContent.SPACE_BETWEEN：两端对齐，元素之间间隔都相等
                     *     JustifyContent.SPACE_AROUND：每个元素两侧的间隔相等，元素之间的间隔比元素与布局边框的间隔要大一倍
                     *     JustifyContent.SPACE_EVENLY：元素之间、元素和布局边框间隔都相等
                     * 交叉轴上对齐方式
                     *     AlignItems.FLEX_START：交叉轴的起点对齐
                     *     AlignItems.FLEX_END：交叉轴的终点对齐
                     *     AlignItems.CENTER：交叉轴的居中对齐
                     *     AlignItems.BASELINE：元素第一行文字的基线对齐
                     *     AlignItems.STRETCH：交叉轴方向占满整个父布局(默认值)
                     */
                    layoutManager = FlexboxLayoutManager(
                        context,
                        FlexDirection.ROW,
                        FlexWrap.WRAP
                    ).apply {
                        justifyContent = JustifyContent.FLEX_START
                        alignItems = AlignItems.FLEX_START
                    }

                    addItemDecoration(
                        FlexboxItemDecoration(context).apply {
                            setDrawable(context.getDrawableEx(R.drawable.rect_flex_space))
                        }
                    )

                    adapter = SlimAdapter.creator()
                        .register<FilterData>(R.layout.pop_member_item) { jector, bean, _ ->
                            jector.apply {
                                with<TextView>(R.id.item_pop_title) {
                                    it.text = bean.name

                                    it.setBackgroundResource(
                                        conditionIf(
                                            bean.isChecked,
                                            R.drawable.member_ova_0d2486f8_stroke_2486f8,
                                            R.drawable.member_ova_0d000000
                                        )
                                    )
                                    it.setTextColor(
                                        context.getColorEx(
                                            conditionIf(
                                                bean.isChecked,
                                                R.color.colorAccent,
                                                R.color.gray
                                            )
                                        )
                                    )
                                }
                                clicked {
                                    val status = bean.isChecked

                                    mVipList
                                        .filter { it.id == bean.id }
                                        .forEach { it.isChecked = false }

                                    bean.isChecked = !status
                                    notifyDataSetChanged()
                                }
                            }
                        }
                        .attachTo(this)

                    (adapter as SlimAdapter).setDataList(mVipList)
                }

                // 会员类型
                val mTypeView = view.find<RecyclerView>(R.id.pop_type).apply {
                    isNestedScrollingEnabled = false
                    layoutManager = FlexboxLayoutManager(
                        context,
                        FlexDirection.ROW,
                        FlexWrap.WRAP
                    ).apply {
                        justifyContent = JustifyContent.FLEX_START
                        alignItems = AlignItems.FLEX_START
                    }

                    addItemDecoration(
                        FlexboxItemDecoration(context).apply {
                            setDrawable(context.getDrawableEx(R.drawable.rect_flex_space))
                        }
                    )

                    adapter = SlimAdapter.creator()
                        .register<FilterData>(R.layout.pop_member_item) { jector, bean, _ ->
                            jector.apply {
                                with<TextView>(R.id.item_pop_title) {
                                    it.text = bean.name

                                    it.setBackgroundResource(
                                        conditionIf(
                                            bean.isChecked,
                                            R.drawable.member_ova_0d2486f8_stroke_2486f8,
                                            R.drawable.member_ova_0d000000
                                        )
                                    )
                                    it.setTextColor(
                                        context.getColorEx(
                                            conditionIf(
                                                bean.isChecked,
                                                R.color.colorAccent,
                                                R.color.gray
                                            )
                                        )
                                    )
                                }
                                clicked {
                                    val status = bean.isChecked

                                    mStateList
                                        .filter { it.id == bean.id }
                                        .forEach { it.isChecked = false }

                                    bean.isChecked = !status
                                    notifyDataSetChanged()
                                }
                            }
                        }
                        .attachTo(this)

                    (adapter as SlimAdapter).setDataList(mStateList)
                }

                // 桶类型
                val mBarrelView = view.find<RecyclerView>(R.id.pop_barrel).apply {
                    isNestedScrollingEnabled = false
                    layoutManager = FlexboxLayoutManager(
                        context,
                        FlexDirection.ROW,
                        FlexWrap.WRAP
                    ).apply {
                        justifyContent = JustifyContent.FLEX_START
                        alignItems = AlignItems.FLEX_START
                    }

                    addItemDecoration(
                        FlexboxItemDecoration(context).apply {
                            setDrawable(context.getDrawableEx(R.drawable.rect_flex_space))
                        }
                    )

                    adapter = SlimAdapter.creator()
                        .register<FilterData>(R.layout.pop_member_item) { jector, bean, _ ->
                            jector.apply {
                                with<TextView>(R.id.item_pop_title) {
                                    it.text = bean.name

                                    it.setBackgroundResource(
                                        conditionIf(
                                            bean.isChecked,
                                            R.drawable.member_ova_0d2486f8_stroke_2486f8,
                                            R.drawable.member_ova_0d000000
                                        )
                                    )
                                    it.setTextColor(
                                        context.getColorEx(
                                            conditionIf(
                                                bean.isChecked,
                                                R.color.colorAccent,
                                                R.color.gray
                                            )
                                        )
                                    )
                                }
                                clicked {
                                    val status = bean.isChecked

                                    mBarrelList
                                        .filter { it.id == bean.id }
                                        .forEach { it.isChecked = false }

                                    bean.isChecked = !status
                                    notifyDataSetChanged()
                                }
                            }
                        }
                        .attachTo(this)

                    (adapter as SlimAdapter).setDataList(mBarrelList)
                }

                // 推荐人
                val mReferView = view.find<RecyclerView>(R.id.pop_jian).apply {
                    isNestedScrollingEnabled = true
                    layoutManager = FlexboxLayoutManager(
                        context,
                        FlexDirection.ROW,
                        FlexWrap.WRAP
                    ).apply {
                        justifyContent = JustifyContent.FLEX_START
                        alignItems = AlignItems.FLEX_START
                    }

                    addItemDecoration(
                        FlexboxItemDecoration(context).apply {
                            setDrawable(context.getDrawableEx(R.drawable.rect_flex_space))
                        }
                    )

                    adapter = SlimAdapter.creator()
                        .register<FilterData>(R.layout.pop_member_item) { jector, bean, _ ->
                            jector.apply {
                                with<TextView>(R.id.item_pop_title) {
                                    it.text = bean.name

                                    it.setBackgroundResource(
                                        conditionIf(
                                            bean.isChecked,
                                            R.drawable.member_ova_0d2486f8_stroke_2486f8,
                                            R.drawable.member_ova_0d000000
                                        )
                                    )
                                    it.setTextColor(
                                        context.getColorEx(
                                            conditionIf(
                                                bean.isChecked,
                                                R.color.colorAccent,
                                                R.color.gray
                                            )
                                        )
                                    )
                                }
                                clicked {
                                    val status = bean.isChecked

                                    mReferItems
                                        .filter { it.id == bean.id }
                                        .forEach { it.isChecked = false }

                                    bean.isChecked = !status

                                    // 无推荐人
                                    (mReferItems[0].isChecked
                                            && mReferItems.size > 2)
                                        .condition {
                                            mReferItems.clear()
                                            mReferItems.addAll(mReferList)
                                            mLeadList.forEach { it.isChecked = false }
                                        }

                                    // 有推荐人
                                    (mReferItems[1].isChecked
                                            && mReferItems.size == 2)
                                        .condition {
                                            mReferItems.addAll(mLeadList)
                                        }

                                    notifyDataSetChanged()
                                }
                            }
                        }
                        .attachTo(this)

                    mReferItems.addAll(mReferList)

                    (mReferList[1].isChecked)
                        .condition {
                            mReferItems.addAll(mLeadList)
                        }

                    (adapter as SlimAdapter).setDataList(mReferItems)
                }

                // 会员交易
                val mTradeView = view.find<RecyclerView>(R.id.pop_trade).apply {
                    isNestedScrollingEnabled = false
                    layoutManager = FlexboxLayoutManager(
                        context,
                        FlexDirection.ROW,
                        FlexWrap.WRAP
                    ).apply {
                        justifyContent = JustifyContent.FLEX_START
                        alignItems = AlignItems.FLEX_START
                    }

                    addItemDecoration(
                        FlexboxItemDecoration(context).apply {
                            setDrawable(context.getDrawableEx(R.drawable.rect_flex_space))
                        }
                    )

                    adapter = SlimAdapter.creator()
                        .register<FilterData>(R.layout.pop_member_item) { jector, bean, _ ->
                            jector.apply {
                                with<TextView>(R.id.item_pop_title) {
                                    it.text = bean.name

                                    it.setBackgroundResource(
                                        conditionIf(
                                            bean.isChecked,
                                            R.drawable.member_ova_0d2486f8_stroke_2486f8,
                                            R.drawable.member_ova_0d000000
                                        )
                                    )
                                    it.setTextColor(
                                        context.getColorEx(
                                            conditionIf(
                                                bean.isChecked,
                                                R.color.colorAccent,
                                                R.color.gray
                                            )
                                        )
                                    )
                                }
                                clicked {
                                    val status = bean.isChecked

                                    mTradeList
                                        .filter { it.id == bean.id }
                                        .forEach { it.isChecked = false }

                                    bean.isChecked = !status
                                    notifyDataSetChanged()
                                }
                            }
                        }
                        .attachTo(this)

                    (adapter as SlimAdapter).setDataList(mTradeList)
                }

                // 会员来源
                val mSourceView = view.find<RecyclerView>(R.id.pop_source).apply {
                    isNestedScrollingEnabled = false
                    layoutManager = FlexboxLayoutManager(
                        context,
                        FlexDirection.ROW,
                        FlexWrap.WRAP
                    ).apply {
                        justifyContent = JustifyContent.FLEX_START
                        alignItems = AlignItems.FLEX_START
                    }

                    addItemDecoration(
                        FlexboxItemDecoration(context).apply {
                            setDrawable(context.getDrawableEx(R.drawable.rect_flex_space))
                        }
                    )

                    adapter = SlimAdapter.creator()
                        .register<FilterData>(R.layout.pop_member_item) { jector, bean, _ ->
                            jector.apply {
                                with<TextView>(R.id.item_pop_title) {
                                    it.text = bean.name

                                    it.setBackgroundResource(
                                        conditionIf(
                                            bean.isChecked,
                                            R.drawable.member_ova_0d2486f8_stroke_2486f8,
                                            R.drawable.member_ova_0d000000
                                        )
                                    )
                                    it.setTextColor(
                                        context.getColorEx(
                                            conditionIf(
                                                bean.isChecked,
                                                R.color.colorAccent,
                                                R.color.gray
                                            )
                                        )
                                    )
                                }
                                clicked {
                                    val status = bean.isChecked

                                    mSourceList
                                        .filter { it.id == bean.id }
                                        .forEach { it.isChecked = false }

                                    bean.isChecked = !status
                                    notifyDataSetChanged()
                                }
                            }
                        }
                        .attachTo(this)

                    (adapter as SlimAdapter).setDataList(mSourceList)
                }

                // 会员其他
                val mOtherView = view.find<RecyclerView>(R.id.pop_other).apply {
                    isNestedScrollingEnabled = false
                    layoutManager = FlexboxLayoutManager(
                        context,
                        FlexDirection.ROW,
                        FlexWrap.WRAP
                    ).apply {
                        justifyContent = JustifyContent.FLEX_START
                        alignItems = AlignItems.FLEX_START
                    }

                    addItemDecoration(
                        FlexboxItemDecoration(context).apply {
                            setDrawable(context.getDrawableEx(R.drawable.rect_flex_space))
                        }
                    )

                    adapter = SlimAdapter.creator()
                        .register<FilterData>(R.layout.pop_member_item) { jector, bean, _ ->
                            jector.apply {
                                with<TextView>(R.id.item_pop_title) {
                                    it.text = bean.name

                                    it.setBackgroundResource(
                                        conditionIf(
                                            bean.isChecked,
                                            R.drawable.member_ova_0d2486f8_stroke_2486f8,
                                            R.drawable.member_ova_0d000000
                                        )
                                    )
                                    it.setTextColor(
                                        context.getColorEx(
                                            conditionIf(
                                                bean.isChecked,
                                                R.color.colorAccent,
                                                R.color.gray
                                            )
                                        )
                                    )
                                }
                                clicked {
                                    val status = bean.isChecked

                                    mOtherList
                                        .filter { it.id == bean.id }
                                        .forEach { it.isChecked = false }

                                    bean.isChecked = !status
                                    notifyDataSetChanged()
                                }
                            }
                        }
                        .attachTo(this)

                    (adapter as SlimAdapter).setDataList(mOtherList)
                }

                view.find<ImageView>(R.id.pop_close).oneClick { dismiss() }
                view.find<TextView>(R.id.pop_reset).oneClick {
                    mVipList.forEach { it.isChecked = false }
                    mStateList.forEach { it.isChecked = false }
                    mBarrelList.forEach { it.isChecked = false }
                    mReferList.forEach { it.isChecked = false }
                    mTradeList.forEach { it.isChecked = false }
                    mSourceList.forEach { it.isChecked = false }
                    mOtherList.forEach { it.isChecked = false }

                    mReferItems.apply {
                        clear()
                        addAll(mReferList)
                    }

                    (mLevelView.adapter as SlimAdapter).notifyDataSetChanged()
                    (mTypeView.adapter as SlimAdapter).notifyDataSetChanged()
                    (mBarrelView.adapter as SlimAdapter).notifyDataSetChanged()
                    (mReferView.adapter as SlimAdapter).notifyDataSetChanged()
                    (mTradeView.adapter as SlimAdapter).notifyDataSetChanged()
                    (mSourceView.adapter as SlimAdapter).notifyDataSetChanged()
                    (mOtherView.adapter as SlimAdapter).notifyDataSetChanged()

                    item = MemberFilterData()
                }
                view.find<TextView>(R.id.pop_done).oneClick {
                    item.vipFlag = if (mVipList.any { it.isChecked }) {
                        mVipList.first { it.isChecked }.hint
                    } else ""

                    item.payFlag = if (mStateList[0].isChecked) "monthly" else ""
                    item.priceFlag = if (mStateList[1].isChecked) 1 else 0
                    item.shipFlag = if (mStateList[2].isChecked) 1 else 0
                    item.barrelFlag = when {
                        mBarrelList[0].isChecked -> 1
                        mBarrelList[1].isChecked -> 2
                        else -> 0
                    }
                    item.borrowFlag = when {
                        mBarrelList[2].isChecked -> 1
                        mBarrelList[3].isChecked -> 2
                        else -> 0
                    }
                    item.referFlag = when {
                        mReferList[0].isChecked -> 2
                        mReferList[1].isChecked -> 1
                        else -> 0
                    }
                    item.referId = if (mLeadList.any { it.isChecked }) {
                        mLeadList.first { it.isChecked }.hint.intValue
                    } else -1
                    item.tradeFlag = when {
                        mTradeList[0].isChecked -> 1
                        mTradeList[1].isChecked -> 2
                        else -> 0
                    }
                    item.sourceFlag = when {
                        mSourceList[0].isChecked -> "pc"
                        mSourceList[1].isChecked -> "app"
                        mSourceList[2].isChecked -> "applet"
                        else -> ""
                    }
                    item.couponFlag = if (mOtherList[0].isChecked) 1 else 0
                    item.memoFlag = if (mOtherList[1].isChecked) 1 else 0

                    item.filterFlag = mVipList.any { it.isChecked }
                            || mStateList.any { it.isChecked }
                            || mBarrelList.any { it.isChecked }
                            || mReferItems.any { it.isChecked }
                            || mTradeList.any { it.isChecked }
                            || mSourceList.any { it.isChecked }
                            || mOtherList.any { it.isChecked }

                    dismiss()
                    onNext(item)
                }
            }

        }

        dropFilter?.showAsDropDown(bottom)
    }

    /**
     * 会员列表
     */
    fun memberList(
        page: Int,
        keyWord: String,
        cardType: String = "",
        exchage: Int = 0,
        filter: MemberFilterData,
        onSuccess: (ArrayList<MemberData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.post<BaseResponse<ResponseModel<MemberData>>>(BaseUrl.memberList)
            .isMultipart(true)
            .params(
                getParams(
                    "searchValue" to keyWord,
                    "cardType" to cardType,
                    "exchangeFlag" to exchage,
                    "vip" to filter.vipFlag,
                    "paymentMethod" to filter.payFlag,
                    "priceFlag" to filter.priceFlag,
                    "autoShipFlag" to filter.shipFlag,
                    "mortgageFlag" to filter.barrelFlag,
                    "borrowFlag" to filter.borrowFlag,
                    "promoterFlag" to filter.referFlag,
                    "promoterId" to filter.referId,
                    "transFlag" to filter.tradeFlag,
                    "source" to filter.sourceFlag,
                    "couponFlag" to filter.couponFlag,
                    "memoFlag" to filter.memoFlag,
                    "pageStart" to page * 10,
                    "pageSize" to 10
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseModel<MemberData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 获取会员总数
     */
    fun getSummary() {
        request(
            isLoadingBefore = false,
            isLoadingAfter = false,
            requestUrl = BaseUrl.memberSum,
            requestMethod = HttpMethod.GET,
            onSuccess = {
                val obj = JSONObject(it)
                mTotalNum.value = obj.optNotNull("all")
                mTradeNum.value = obj.optNotNull("buy")
            }
        )
    }

    /**
     * 会员详情
     */
    fun memberDetail(cardId: String) =
        RxSingleHelper.requestString(
            url = BaseUrl.memberInfo,
            params = getParams("id" to cardId)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 会员修改
     */
    fun memberModify(vararg params: Pair<String, Any>) =
        RxSingleHelper.requestString(
            url = BaseUrl.memberUpdate,
            isMultipart = true,
            params = getParams(*params)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 消费记录
     */
    fun memberOrder(
        page: Int,
        memberId: String,
        beginDate: String,
        endDate: String,
        onSuccess: (ArrayList<Any>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<OrderModel>>(BaseUrl.orderList)
            .params(
                getParams(
                    "memberId" to memberId,
                    "beginDate" to beginDate.ifNotEmpty { "$it 00:00:00" },
                    "endDate" to endDate.ifNotEmpty { "$it 23:59:59" },
                    "pageStart" to page * 20,
                    "pageSize" to 20
                )
            )
            .converter(object : JacksonConvert<BaseResponse<OrderModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map {
                ArrayList<Any>().apply {
                    it.data.data.forEachIndexed { index, item ->
                        // 添加头部
                        add(OrderHeader().apply {
                            position = index
                            orderSN = item.sn
                            shippingSn = item.shippingSn.orEmpty()
                            status_hint = item.statusDescr
                            hint = "下单时间："
                            time = item.createDate.getTimeString()
                        })

                        // 添加商品
                        addItems(
                            item.orderItems.onEach {
                                it.orderSN = item.sn
                                it.shippingSn = item.shippingSn.orEmpty()
                                it.position = index
                                it.hopeDate = item.hopeDate.orEmpty()
                                it.fast = item.isFast
                                it.first = item.isFisrst
                            }
                        )

                        // 添加底部
                        add(OrderFooter().apply {
                            position = index
                            orderSN = item.sn
                            shippingSn = item.shippingSn.orEmpty()
                            status = item.status.orEmpty()
                            total_num = item.quantity
                            amount = item.amountPaid.orEmpty()
                            amountHint = "实付款: "
                            name = item.consignee.orEmpty()
                            phone = item.phone.orEmpty()
                            address = item.address
                            memo = item.memo.orEmpty()
                            adminName = item.adminName.orEmpty()
                            createDate = item.createDate.getTimeString()
                            hopeDate = item.hopeDate.getTimeString()
                        })
                    }
                }
            }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 会员推广
     */
    fun shareList(
        page: Int,
        memberId: String,
        beginDate: String,
        endDate: String,
        onSuccess: (ArrayList<MemberData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ResponseModel<MemberData>>>(BaseUrl.stsShareDet)
            .params(
                getParams(
                    "memberId" to memberId,
                    "beginDate" to beginDate.ifNotEmpty { "$it 00:00:00" },
                    "endDate" to endDate.ifNotEmpty { "$it 23:59:59" },
                    "pageStart" to page * 20,
                    "pageSize" to 20
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseModel<MemberData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 推广员列表（含员工）
     */
    fun promoterList(
        page: Int,
        keyWord: String,
        onSuccess: (ArrayList<PromoterData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.post<BaseResponse<ArrayList<PromoterData>>>(BaseUrl.memberPros)
            .isMultipart(true)
            .params(
                getParams(
                    "searchValue" to keyWord,
                    "pageStart" to page * 20,
                    "pageSize" to 20
                )
            )
            .converter(object : JacksonConvert<BaseResponse<ArrayList<PromoterData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 记账商品列表
     */
    fun billList(
        cardId: String,
        onSuccess: (ArrayList<GoodsData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ArrayList<GoodsData>>>(BaseUrl.memberBill)
            .params(
                getParams("id" to cardId)
            )
            .converter(object : JacksonConvert<BaseResponse<ArrayList<GoodsData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 改价列表
     */
    fun changeList(
        page: Int,
        member: String,
        onSuccess: (ArrayList<GoodsData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ResponseModel<GoodsData>>>(BaseUrl.memberPrice)
            .params(
                getParams(
                    "memberId" to member,
                    "pageStart" to page * 30,
                    "pageSize" to 30
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseModel<GoodsData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 休眠会员
     */
    fun offlineList(
        page: Int,
        onSuccess: (ArrayList<BillWorkerData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ResponseModel<BillWorkerData>>>(BaseUrl.mngOffline)
            .params(
                getParams(
                    "pageStart" to page * 10,
                    "pageSize" to 10
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseModel<BillWorkerData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 休眠会员回访记录
     */
    fun visitList(
        page: Int,
        cardId: String,
        onSuccess: (ArrayList<OfflineRecord>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ArrayList<OfflineRecord>>>(BaseUrl.mngVisitList)
            .params(
                getParams(
                    "id" to cardId,
                    "pageStart" to page * 20,
                    "pageSize" to 20
                )
            )
            .converter(object : JsonConvert<BaseResponse<ArrayList<OfflineRecord>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 水票提醒
     */
    fun warnList(
        page: Int,
        onSuccess: (ArrayList<BillWorkerData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ResponseModel<BillWorkerData>>>(BaseUrl.mngWarn)
            .params(
                getParams(
                    "pageStart" to page * 10,
                    "pageSize" to 10
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseModel<BillWorkerData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

}